﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using WriteLog;

namespace TakeConsole
{
    public class TakeConsoleWriter : StringWriter
    {
        /// <summary>
        /// 原控制台输出TextWriter
        /// </summary>
        private TextWriter OldTextWriter;

        /// <summary>
        /// 构造函数
        /// 调用构造函数将记录Console的输出（限定：WriteLine方法）
        /// </summary>
        /// <param name="oldTextWriter"></param>
        public TakeConsoleWriter()
        {
            OldTextWriter = Console.Out;
            this.Start();
        }

        /// <summary>
        /// 重写了TextWrite的方法
        /// 可以接管Console.WriteLine的内容，然后触发事件
        /// </summary>
        /// <param name="value"></param>
        public override void WriteLine(string value)
        {
            #region 不接管WriteLog名称空间以下的Console.WriteLine
            bool isSelf = false;
            StackTrace st = new StackTrace();
            foreach (StackFrame sf in st.GetFrames())
            {
                isSelf = sf.GetMethod().DeclaringType.Namespace == typeof(ISaveLog).Namespace;
                if (isSelf) break;
            }
            #endregion

            if (!isSelf)
            {
                Log.Console(value);
            }
            OldTextWriter.WriteLine(value);
            base.WriteLine(value);
        }

        /// <summary>
        /// 编码
        /// </summary>
        public override Encoding Encoding
        {
            get { return Encoding.Default; }
        }

        /// <summary>
        /// 开始接管
        /// </summary>
        public void Start()
        {
            Console.SetOut(this);
        }

        /// <summary>
        /// 不需要接管Console.WriteLine时，调用此方法
        /// </summary>
        public void Stop()
        {
            Console.SetOut(OldTextWriter);
        }
    }
}
